package com.qf.oa_system.controller;

import com.qf.oa_system.entity.*;
import com.qf.oa_system.service.ScoreService;
import com.qf.oa_system.service.TeacherService;
import com.qf.oa_system.service.WeeklyService;
import com.qf.oa_system.util.ExcelExport;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

/**
 * ??ʦ?(Teacher)表控制层
 *
 * @author makejava
 * @since 2020-06-03 20:26:32
 */
@Controller
@RequestMapping("teacher")
public class TeacherController {
    /**
     * 服务对象
     */
    @Resource
    private TeacherService teacherService;

    @Resource
    private WeeklyService weeklyService;

    @Resource
    private ScoreService scoreService;

    @PostMapping("/mark")
    public String mark(Integer weekId, Integer score){
        teacherService.mark(weekId, score);
        return "redirect:/teacher/weeklySee";
    }

    @GetMapping("/modifyInformation")
    public String modifyInformation(ModelMap modelMap, HttpSession httpSession){

        User user = (User) httpSession.getAttribute("user");

        Teacher teacher = teacherService.getTeacherByUserId(user.getUserId());
        modelMap.put("teacher", teacher);
        return "teacherInfo";
    }

    @PostMapping("/modifyInformation")
    public String modifyInformation(Teacher teacher){
        teacherService.update(teacher);
        return "redirect:/";
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Teacher selectOne(Integer id) {
        return this.teacherService.queryById(id);
    }

    @ResponseBody
    @PostMapping("/modify")
    public String modifyGrade(String scoreId, String score){

        Score s = new Score();
        s.setScoreId(Integer.parseInt(scoreId));
        s.setScoreGrade(Integer.parseInt(score));
        scoreService.update(s);

        return "success";
    }

    @GetMapping("/toLeave")
    public String leave(){
        return  "teacherLeave";
    }

    @GetMapping("/weeklySee")
    public String weeklySee(ModelMap modelMap){

        List<Weekly> weeklies = weeklyService.queryAll(null);
        System.out.println(weeklies);
        modelMap.put("weeklies", weeklies);

        return "teaWeeklySee";
    }

    @GetMapping("/toAchievementsRecord")
    public String achievementsRecord(ModelMap modelMap, HttpSession session){

        User user = (User) session.getAttribute("user");
        List<StudentAndSingleScore> scoreAndStudents = teacherService.getStudentAndScoreByCouAndCla(user.getUserId());

        modelMap.put("scoreAndStudents", scoreAndStudents);
        return "stuTeaScore";
    }


    @GetMapping("/performanceAnalysis")
    public String performanceAnalysis(){

        return "performanceAnalysis";
    }


    @GetMapping("/toStuInfo")
    public String toStuInfo(ModelMap modelMap, HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) session.getAttribute("user");
        if (subject.hasRole("admin")){
            return "redirect:/classmaster/toStudentsInformtion";
        }
        List<Student> studentInfo = teacherService.getStudentInfo(user.getUserId());

        modelMap.put("stuList", studentInfo);

        return "stuinfo";
    }

    @ResponseBody
    @GetMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {

        User user = (User) session.getAttribute("user");
        List<Student> studentInfo = teacherService.getStudentInfo(user.getUserId());

        String[] title = {"姓名", "性别","生日", "电话", "地址"};
        String sheetName = "sheet1";
        String filename = "stuPort.xls";
        String[][] content = new String[studentInfo.size()][5];

        for (int i = 0; i < studentInfo.size(); i++) {
            content[i][0] = studentInfo.get(i).getStuName();
            content[i][1] = studentInfo.get(i).getStuSex();
            content[i][2] = studentInfo.get(i).getStuBirthday();
            content[i][3] = studentInfo.get(i).getStuPhone();
            content[i][4] = studentInfo.get(i).getStuAddress();
        }
        HSSFWorkbook wb = ExcelExport.getHSSFWorkbook(sheetName, title, content, null);

        // 响应到客户端
        this.setResponseHeader(response, filename);
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}